import React, { useEffect, useState, useRef } from 'react';
import { Layout, Card, Button, Space, Spin, Empty } from 'antd';
import { trendAnalysisApi } from 'services/trend-analysis';
import MainLayout from 'components/MainLayout';
import { API_URL } from 'constant';

import styles from './Trend.module.css';

const INDUSTRIES = [
  '新材料',
  '人参',
  '大农业',
  '大装备',
  '大数据',
  '新能源',
  '新医药',
  '光电信息',
  '量子技术',
  '人工智能',
] as const;

type Industry = (typeof INDUSTRIES)[number];

const TrendAnalysis: React.FC = () => {
  const [selectedIndustry, setSelectedIndustry] = useState<Industry>('新材料');
  const [chartHtmls, setChartHtmls] = useState<{ [key: string]: string }>({});
  const [loading, setLoading] = useState<boolean>(true);

  // 添加初始化标记和上一次的产业值追踪
  const prevIndustry = useRef<string | null>(null);

  // 添加获取图表HTML的函数
  const fetchChartHtml = async (chartType: string, industry: string) => {
    setLoading(true);

    try {
      const response = await trendAnalysisApi.getTrendChartHtml(
        chartType,
        industry
      );

      if (response.code !== 200) {
        throw new Error('获取图表失败');
      }

      if (!response.data?.imageUrl) {
        setChartHtmls((prev) => ({
          ...prev,
          [chartType]: '',
        }));
      } else {
        const imageUrl = response.data?.imageUrl;
        const html = imageUrl.replace('/trend/output', '');
        setChartHtmls((prev) => ({
          ...prev,
          [chartType]: html,
        }));
      }
    } catch (error) {
      console.error(`获取${chartType}图表失败:`, error);
    } finally {
      setLoading(false);
    }
  };

  // 封装获取所有图表的方法
  const fetchAllCharts = (industry: string) => {
    const chartTypes = [
      'heatmap',
      'barchart',
      'linechart',
      'scatter',
      'bubble',
      'wordcloud',
    ];

    chartTypes.forEach((type) => fetchChartHtml(type, industry));
  };

  // 使用 ref 控制调用
  useEffect(() => {
    if (selectedIndustry && selectedIndustry !== prevIndustry.current) {
      prevIndustry.current = selectedIndustry;
      setLoading(true);
      fetchAllCharts(selectedIndustry);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectedIndustry]);

  const renderChartCard = (
    title: string,
    chartType: string,
    className: string
  ) => {
    return (
      <Card
        className={`${styles.chart} ${styles[className]}`}
        bodyStyle={{ padding: 0 }}
        bordered={false}
      >
        <h3>{title}</h3>

        {loading && <Spin spinning={loading} className={styles.spin} />}

        {!loading && chartHtmls[chartType] && (
          <iframe
            title={chartType}
            src={API_URL + chartHtmls[chartType]}
            className={styles.chartFrame}
            sandbox="allow-scripts allow-same-origin"
          />
        )}

        {!loading && !chartHtmls[chartType] && (
          <Empty description="暂无数据" style={{ marginTop: 100 }}   />
        )}
      </Card>
    );
  };

  return (
    <MainLayout>
      <Layout className={styles.layout}>
        <Layout.Sider width={280} className={styles.sider}>
          <Card
            title="产业选择"
            bordered={false}
            className={styles.industryCard}
          >
            <Space direction="vertical" style={{ width: '100%' }}>
              {INDUSTRIES.map((industry) => (
                <Button
                  key={industry}
                  type="default"
                  onClick={() => setSelectedIndustry(industry)}
                  className={`${styles.industryButton} ${
                    selectedIndustry === industry ? styles.selectedIndustry : ''
                  }`}
                  block
                >
                  {industry}
                </Button>
              ))}
            </Space>
          </Card>
        </Layout.Sider>
        <Layout.Content className={styles.content}>
          <div className={styles.chartGrid}>
            {renderChartCard('全国专利分布图', 'heatmap', 'gradientBg1')}
            {renderChartCard('TOP10专利机构分布图', 'barchart', 'gradientBg2')}
            {renderChartCard(
              'TOP5产业核心词趋势图',
              'linechart',
              'gradientBg3'
            )}
            {renderChartCard('产业核心词活跃图', 'scatter', 'gradientBg4')}
            {renderChartCard('产业热词共现图', 'bubble', 'gradientBg5')}
            {renderChartCard('产业热词词云图', 'wordcloud', 'gradientBg6')}
          </div>
        </Layout.Content>
      </Layout>
    </MainLayout>
  );
};

export default TrendAnalysis;
